package com.tim.framework.util;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.util.Arrays;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * 密码加密.
 * 
 * @author Tim.
 */
public class Password {
	private static final int SALT_ORIGINAL_LEN = 8;

	private static final int SALT_ENCODED_LEN = 12;

	/**
	 * 获取加密数据.
	 * 
	 * @param data
	 *            需要加密的数据.
	 */
	public static String digestData(String data) {
		try {
			SecureRandom random = new SecureRandom();
			byte[] salt = new byte[SALT_ORIGINAL_LEN];
			random.nextBytes(salt);

			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(salt);
			md.update(data.getBytes());
			byte[] digest = md.digest();

			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(salt) + encoder.encode(digest);
		} catch (NoSuchAlgorithmException ne) {
			System.out.println(ne.toString());
			return null;
		} catch (Exception e) {
			System.out.println(e.toString());
			return null;
		}
	}

	/**
	 * 验证数据是否与密文数据相同.
	 * 
	 * @param password
	 *            用户输入的数据，如：123456
	 * @param cipher
	 *            密文数据.
	 */
	public static boolean validateData(String data, String cipher) {
		boolean label = false;
		try {
			String salt_str = cipher.substring(0, SALT_ENCODED_LEN);
			String digest_str = cipher.substring(SALT_ENCODED_LEN, cipher
					.length());
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] salt = decoder.decodeBuffer(salt_str);
			byte[] digest_old = decoder.decodeBuffer(digest_str);

			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(salt);
			md.update(data.getBytes());
			byte[] digest_new = md.digest();
			label = Arrays.equals(digest_old, digest_new);
		} catch (NoSuchAlgorithmException ne) {
			System.out.println(ne.toString());
		} catch (IOException ie) {
			System.out.println(ie.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return label;
	}
}
